# -*- coding: utf-8 -*-

'''
@project : SmartHomeVideo
@FileName: face_analysis_main
@Author  :linych 
@Time    :2021/2/23 14:18
@Desc  : 
'''

import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import pika
import json
from FaceAnalysis.async_yitu_strange_recognite_task import StrangeRecogTask
from Core.redis_connecter import redis_Param,redis_Task, TASK_NAME
import time
from Core import conf
import asyncio
from MQ.mq_connect_util import MQ_connect

host = conf.get('MQ', 'url')
username = conf.get('MQ', 'username')
pwd = conf.get('MQ', 'pwd')
queue = conf.get('MQ', 'queue')

# 建立连接，服务器地址为localhost，可指定ip地址


loop = asyncio.new_event_loop()

RL = []

mq_client = MQ_connect(host=host,username=username,pwd=pwd,queue=queue)


async def face_run(seqid, deviceId, visitorId, imageBase64s_list, routing_key, correlation_id):
    global RL

    try:

        s = time.time()

        result = await StrangeRecogTask.run(seqid=seqid, deviceId=deviceId, visitorId=visitorId,
                                            imageBase64s_list=imageBase64s_list)

        print(result)
        RL.append((correlation_id, routing_key, result))

        print('face_run use :{}'.format(time.time() - s))

    except Exception as e:
        print('error face_run :{}..................'.format(e))


def run(correlation_id, loop):
    try:

        arg_dict = redis_Param.hgetall(correlation_id)

        routing_key = arg_dict.get('routing_key', '')
        seqid = arg_dict.get('seqid', '')
        deviceId = arg_dict.get('deviceId', '')
        visitorId = arg_dict.get('visitorId', '')

        pic_id_list = redis_Task.lrange(correlation_id, 0, -1)

        imageBase64s_list = redis_Task.mget(list(pic_id_list))

        asyncio.run_coroutine_threadsafe(
            face_run(seqid, deviceId, visitorId, imageBase64s_list, routing_key, correlation_id), loop)


    except Exception as e:
        print(e)


def face_main():
    global RL

    while True:

        correlation_id = redis_Task.lpop(TASK_NAME)

        if correlation_id is None:
            time.sleep(0.001)
            # print('wait')
            continue

        if len(RL) > 100:
            print('RL : {}'.format(len(RL)))
            time.sleep(0.001)
            continue
        try:

            print('analysis {}....'.format(correlation_id))
            run(correlation_id, loop=loop)

        except Exception as e:

            print('error face_main {}......'.format(e))


def start_loop(loop):
    asyncio.set_event_loop(loop)
    print("start loop", time.time())
    loop.run_forever()
    print(asyncio.Task.all_tasks().pop().result())


def replay_res():
    global RL

    while True:
        try:
            # print('replay : {}'.format(len(RL)))
            data = RL.pop(0)
        except:
            # 取不到结果数据
            data = None

        try:

            if data is None:
                # print('sleep')
                time.sleep(0.01)
                continue

            correlation_id, routing_key, result = data

            channel = mq_client.get_channel()

            channel.basic_publish(exchange='',
                                  routing_key=routing_key,
                                  properties=pika.BasicProperties(correlation_id=correlation_id),
                                  body=str(result))

            print('publish {}.....'.format(correlation_id))

        except Exception as e:

            print('publish error.....'.format(e))


if __name__ == '__main__':

    import threading

    threads = []

    face_worker = 1

    for i in range(face_worker):
        t = threading.Thread(target=face_main)
        threads.append(t)
        t.start()

    t = threading.Thread(target=replay_res)

    t.start()

    start_loop(loop=loop)
